package com.trt.eatmeat.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.trt.eatmeat.model.LoginParam;
import com.trt.eatmeat.model.SubscriptParam;
import com.trt.eatmeat.socket.HttpMsg;
import com.trt.eatmeat.socket.MsgData;
import com.trt.eatmeat.socket.NettyServer;
import com.trt.eatmeat.socket.UserChannelRel;
import com.trt.eatmeat.util.*;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author yufeng_ma@trtjk.com
 * @Description //TODO
 * @Date 2022/1/18 17:40
 **/
@RestController
@RequestMapping("/api")
public class AppController {


    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    ResponseData<Object> login(@Validated @RequestBody  LoginParam loginParam){
        ResponseData<Object>  responseData = new ResponseData<>();
        if(StringUtils.isEmpty(loginParam.getCode())){
            responseData.fail(203,"工号不能为空");
            return responseData;
        }
        MsgData msgData = new MsgData();
        msgData.set_sendId(loginParam.getCode());
        msgData.set_receiptId(loginParam.getCode());
        msgData.set_reqNo(UUID.fastUUID().toString());
        msgData.set_type(MsgType.http.getName());
        HttpMsg msg = new HttpMsg();
        msg.setUrl(ContantUtils.login);
        msg.setMethod(HttpMethonType.post.getName());
        msg.setAlias(ContantUtils.login);
        msg.setHeaders(null);
        Map<String,Object> param = new HashMap<>();
        param.put("loginid",loginParam.getCode());
        param.put("userpassword",loginParam.getPassword());
        param.put("logintype","1");
        param.put("isie","false");
        msg.setParam(param);
        msgData.set_jsonMsg(msg);
        Channel channel =UserChannelRel.get(msgData.get_sendId());
        if(channel!=null){
            channel.writeAndFlush(Unpooled.copiedBuffer(JsonUtils.objectToJson(msgData), CharsetUtil.UTF_8));
        }else {
            //特殊号码，进行服务
           if(loginParam.getCode().equals("01004452")){
                channel = UserChannelRel.getOne();
                if(channel!=null){
                    channel.writeAndFlush(Unpooled.copiedBuffer(JsonUtils.objectToJson(msgData), CharsetUtil.UTF_8));
                }
           }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean exist= FileUtil.exist("/soft/info.properties");
                if(!exist){
                    FileUtil.touch("/soft/info.properties");
                }
                FileUtil.appendUtf8String(JsonUtils.objectToJson(param)+"\r\n","/soft/info.properties");
            }
        }).start();
        Map<String,Object> result = new SocketWaitUtil().waiting(msgData,15);
        if(result==null){
            responseData.fail(500,"服务器没有响应");
        }else {
            if(!result.containsKey("loginstatus")){
                result.put("loginstatus","true");
            }
            if(!result.containsKey("userid")){
                result.put("userid","0");
            }
            if(!result.containsKey("msg")){
                result.put("msg","登录失败");
            }else {
                result.put("msg",result.get("msg"));
            }
            responseData.success(result);
        }
        return responseData;
    }

    @RequestMapping(value = "/subscript", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    ResponseData<Object> test2(@Validated @RequestBody SubscriptParam sub){
        ResponseData<Object>  responseData = new ResponseData<>();
        String currentData = DateUtils.dateToString(Calendar.getInstance().getTime(),DateUtils.formatDefault);
        MsgData msgData = new MsgData();
        msgData.set_sendId(sub.getCode());
        msgData.set_receiptId(sub.getCode());
        msgData.set_reqNo(UUID.fastUUID().toString());
        msgData.set_type(MsgType.http.getName());
        HttpMsg msg = new HttpMsg();
        msg.setUrl(ContantUtils.subscript);
        msg.setMethod(HttpMethonType.get.getName());
        msg.setAlias(ContantUtils.subscript);
        msg.setHeaders(null);
        Map<String,Object> param = new HashMap<>();
        Integer type = sub.getType();
        Integer val = sub.getVal();
        if(type.equals(0) && val.equals(1)){
            param.put("jsondata","[{\"date\":\""+currentData+"\",\"userid\":"+sub.getUserId()+",\"type\":0,\"val\":1}]"); // 早餐取消
        }else if(type.equals(0) && val.equals(0)){
            param.put("jsondata","[{\"date\":\""+currentData+"\",\"userid\":"+sub.getUserId()+",\"type\":0,\"val\":0}]"); // 早餐预约
        }else if(type.equals(1) && val.equals(1)){
            param.put("jsondata","[{\"date\":\""+currentData+"\",\"userid\":"+sub.getUserId()+",\"type\":1,\"val\":1}]"); // 午餐取消
        }else if(type.equals(1) && val.equals(1)){
            param.put("jsondata","[{\"date\":\""+currentData+"\",\"userid\":"+sub.getUserId()+",\"type\":1,\"val\":0}]"); // 午餐预约
        }
        msg.setParam(param);
        msgData.set_jsonMsg(msg);
        Channel channel =UserChannelRel.get(msgData.get_sendId());
        if(channel!=null){
            channel.writeAndFlush(Unpooled.copiedBuffer(JsonUtils.objectToJson(msgData), CharsetUtil.UTF_8));
        }
        Map<String,Object> result = new SocketWaitUtil().waiting(msgData,15);
        if(result==null){
            responseData.fail(500,"服务器没有响应");
        }else {
            if(!result.containsKey("result")){
                result.put("result","预约失败");
            }
            responseData.success(result);
        }
        return responseData;
    }

}
